package com.push.api.servlet;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;

import com.push.api.db.DbUtil;
import com.push.api.vo.PushLog;

public class PushLogAPI extends BaseSerlvet {

    /**
     * 
     */
    private static final long serialVersionUID = 3480713167810438415L;

    private ObjectMapper mapper = new ObjectMapper();
    
    @Override
    protected void handle(HttpServletRequest request, HttpServletResponse response) {
        
        String device = request.getParameter("device");
        String appPackagename = request.getParameter("app");
        String offerid = request.getParameter("offer");
        String type = request.getParameter("type");
        String packagename = request.getParameter("package");
        
        System.out.println(device + "|" + appPackagename + "|" + offerid + "|" + type + "|" + packagename);
        
        if (device == null || device.equals("") || appPackagename == null || appPackagename.equals("") || 
                offerid == null || offerid.equals("") || type == null || type.equals("") || 
                packagename == null || packagename.equals("")) {
            try {
                mapper.writeValue(response.getWriter(), "invalid request");
            } catch (JsonGenerationException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (JsonMappingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return;
        }
        
        PushLog log = new PushLog();
        log.setApp_packagename(appPackagename);
        log.setDevice(device);
        log.setOffer_packagename(packagename);
        log.setOfferid(Integer.valueOf(offerid));
        log.setType(type);
        
        DbUtil.insertPushLog(log);
        
        try {
            mapper.writeValue(response.getWriter(), "success");
        } catch (JsonGenerationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (JsonMappingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}
